package com.zzhou.linkinfo.clock.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.zzhou.linkinfo.clock.R;
import com.zzhou.linkinfo.clock.activity.base.AbstractTitleActivity;
import com.zzhou.linkinfo.clock.customview.ListViewForScrollView;
import com.zzhou.linkinfo.clock.entity.Grade;
import com.zzhou.linkinfo.clock.entity.Group;
import com.zzhou.linkinfo.clock.entity.Person;
import com.zzhou.linkinfo.clock.mvp.releasetask.ISelectContactsContract;
import com.zzhou.linkinfo.clock.mvp.releasetask.SelectContactsPresenter;
import com.zzhou.linkinfo.clock.util.node.Node;
import com.zzhou.linkinfo.clock.util.node.SimpleTreeAdapter;
import com.zzhou.linkinfo.clock.util.SharedPreferencesUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Select contacts.
 * Created by Carlos on 2019/03/15
 */
public class ClockSelectContactsActivity extends AbstractTitleActivity implements ISelectContactsContract.IView {
    public static final String RECEIVER_RESULT = "receiverResult";
    public static final String CHOSEN_RECEIVERS = "chosenReceivers";

    private ListViewForScrollView mTree;
    private Button mComplete;

    private List<Node> mData;
    private SimpleTreeAdapter mAdapter;
    private ArrayList<Group> mGroups;
    private ArrayList<Group> mChooseReceivers;
    private List<Node> mRecordData;//记录用户展开的数据
    private SharedPreferencesUtils mSharedPreferencesUtils;

    private ISelectContactsContract.APresenter mPresenter;

    @Override
    protected int attachLayoutRes() {
        return R.layout.clock_activity_select_contacts;
    }

    @Override
    protected void initView() {
        mTree = findViewById(R.id.lv_tree);
        mComplete = findViewById(R.id.complete);

        mData = new ArrayList<>();
        mPresenter = new SelectContactsPresenter(this);

        mSharedPreferencesUtils = new SharedPreferencesUtils(this, "NodeRecord_" + /*getCurAccount().getUserId()*/1111);
        Bundle bundle = getIntent().getExtras();
        mChooseReceivers = (ArrayList<Group>) bundle.getSerializable(CHOSEN_RECEIVERS);
        String recordDataStr = mSharedPreferencesUtils.getObject("record", String.class);
        mRecordData = Node.parseJson(recordDataStr);
        if (mChooseReceivers == null) {
            mChooseReceivers = new ArrayList<>();
            mRecordData = new ArrayList<>();//如果上一个页面没选人，清空
        }

//        ((SelectContactsPresenter) mPresenter).request();
        test();

        mComplete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSharedPreferencesUtils.setObject("record", Node.toJson(mData));
                if (mGroups == null) {
                    mGroups = new ArrayList<>();
                }
                mGroups.clear();
                mGroups.addAll(convertNodeToGroup(mData));
                Intent intent = new Intent();
                intent.putExtra(RECEIVER_RESULT, mGroups);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    private List<Grade> setTestData() {
        List<Grade> grades = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Grade grade = new Grade();
            grade.setId(i + 2);
            grade.setName("carlos " + i);
            List<Person> people = new ArrayList<>();
            for (int j = 0; j < 3; j++) {
                Person person = new Person();
                person.setId(j + 22);
                person.setName("person " + j);
                people.add(person);
            }
            grade.setPeople(people);

            grades.add(grade);
        }
        return grades;
    }

    private void test() {
        List<Grade> grades = setTestData();
        if (grades != null && grades.size() > 0) {//年级
            Node nodeAll = new Node(1, -1, Node.Level_Top, new Person(0, "全部"));
            mData.add(nodeAll);

            for (int i = 0; i < grades.size(); i++) {
                Grade grade = grades.get(i);
                Node nodeGrade = new Node(grade.getId(), 1, Node.Level_Class, new Person(0, grade.getName()));
                mData.add(nodeGrade);

                List<Person> peopleArray = grade.getPeople();
                if (peopleArray != null && peopleArray.size() > 0) {
                    for (int j = 0; j < peopleArray.size(); j++) {
                        Node nodeClass = new Node(peopleArray.get(j).getId(), nodeGrade.getId(), Node.Level_Member, new Person(0, peopleArray.get(j).getName()));
                        mData.add(nodeClass);
                    }
                }
            }
        }
        mAdapter = new SimpleTreeAdapter(mTree, ClockSelectContactsActivity.this, mData, 1,
                R.drawable.clock_select_contacts_arrow_down, R.drawable.clock_select_contacts_arrow_right);
        mTree.setAdapter(mAdapter);

        List<Node> choose = convertGroupToNode(mChooseReceivers);
        refreshNodeChecked(choose);
        refreshNodeExpand(mRecordData);
    }

    @Override
    public void onShowResult(boolean isSuccess, List<Grade> grades) {

        if (grades != null && grades.size() > 0) {//年级
            Node nodeAll = new Node(1, -1, Node.Level_Top, new Person(0, "全部"));
            mData.add(nodeAll);

            for (int i = 0; i < grades.size(); i++) {
                Grade grade = grades.get(i);
                Node nodeGrade = new Node(grade.getId(), 1, Node.Level_Class, new Person(0, grade.getName()));
                mData.add(nodeGrade);

                List<Person> peopleArray = grade.getPeople();
                if (peopleArray != null && peopleArray.size() > 0) {
                    for (int j = 0; j < peopleArray.size(); j++) {
                        Node nodeClass = new Node(peopleArray.get(j).getId(), nodeGrade.getId(), Node.Level_Member, new Person(0, peopleArray.get(j).getName()));
                        mData.add(nodeClass);
                    }
                }
            }
        }
        mAdapter = new SimpleTreeAdapter(mTree, ClockSelectContactsActivity.this, mData, 1,
                R.drawable.clock_select_contacts_arrow_down, R.drawable.clock_select_contacts_arrow_right);
        mTree.setAdapter(mAdapter);

        List<Node> choose = convertGroupToNode(mChooseReceivers);
        refreshNodeChecked(choose);
        refreshNodeExpand(mRecordData);
    }

    private List<Node> convertGroupToNode(List<Group> groups) {
        List<Node> nodes = new ArrayList<>();
        if (groups != null && groups.size() > 0) {
            for (Group group : groups) {
                long parentId = getGradeIdFromGroupId(group.getId());
                if (parentId != 0) {
                    Node nodeGroup = new Node(group.getId(), getGradeIdFromGroupId(group.getId()), Node.Level_Class, new Person(0, group.getName()));
                    nodeGroup.setChecked(group.isChecked());
                    nodes.add(nodeGroup);
                    List<Person> persons = group.getPersons();
                    if (persons != null && persons.size() > 0) {
                        for (Person person : persons) {
                            Node node = new Node(person.getId(), group.getId(), Node.Level_Member, person);
                            if (nodeGroup.isChecked()) {
                                node.setChecked(true);
                            } else {
                                node.setChecked(person.isChecked());
                            }
                            if (node.getParent() != null) {
                                node.getParent().setExpand(true);
                            }
                            nodes.add(node);
                        }
                    }
                }
            }
        }
        return nodes;
    }

    private void refreshNodeChecked(List<Node> choose) {
        for (Node node : mData) {
            for (Node cNode : choose) {
                if (cNode.getMyLevel() == node.getMyLevel() && cNode.getpId() == node.getpId() && cNode.getId() == node.getId()) {
                    node.setChecked(cNode.isChecked());
                    node.setExpand(cNode.isExpand());
                    mAdapter.setChecked(node, cNode.isChecked());
                }
            }
        }

    }

    private void refreshNodeExpand(List<Node> choose) {
        for (Node node : mData) {
            for (Node cNode : choose) {
                if (cNode.getMyLevel() == node.getMyLevel() && cNode.getpId() == node.getpId() && cNode.getId() == node.getId()) {
                    node.setExpand(cNode.isExpand());
                    if (node.isExpand()) {
                        mAdapter.expand(node);
                    }
                }
            }
        }
    }

    private List<Group> convertNodeToGroup(List<Node> nodes) {
        List<Group> groups = new ArrayList<>();
        List<Person> persons = new ArrayList<>();
        if (nodes != null && nodes.size() > 0) {
            for (Node node : nodes) {
                if (node.getMyLevel() == Node.Level_Class) {
                    Group group = new Group();
                    group.setId(node.getId());
                    group.setName(node.getBean().getName());
                    group.setChecked(node.isChecked());
                    groups.add(group);
                } else if (node.getMyLevel() == Node.Level_Member) {
                    Person person = new Person();
                    person.setId(node.getId());
                    person.setGroupId(node.getpId());
                    person.setName(node.getBean().getName());
                    person.setChecked(node.isChecked());
                    persons.add(person);
                }
            }
        }
        for (Group group : groups) {
            for (Person person : persons) {
                if (person.getGroupId() == group.getId()) {
                    if (group.getPersons() == null) {
                        group.setPersons(new ArrayList<Person>());
                    } else {

                    }
                    group.getPersons().add(person);
                }
            }

        }
        return groups;
    }

    private long getGradeIdFromGroupId(long id) {
        for (Node node : mData) {
            if (node.getMyLevel() == Node.Level_Class && node.getId() == id) {
                return node.getpId();
            }
        }
        return 0;
    }
}
